package net.pixiewebdesign.flightinfo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.net.URL;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class FlightInfoActivity extends Activity {

	// private Handler mHandler = new Handler(Looper.getMainLooper());
	public Context m;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_flight_info);
		m = this;

		class FetchJSONDataTask extends AsyncTask<String, Void, JSONObject> {

			// This gets executed on a background thread
			protected JSONObject doInBackground(String... params) {
				Looper.prepare();
				Toast.makeText(m, "Loading JSON..", Toast.LENGTH_SHORT).show();
				String urlString = params[0];
				String jsonData;
				JSONObject weatherJSONObject = null;
				try {
					jsonData = readUrl(urlString);
					weatherJSONObject = new JSONObject(jsonData);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Looper.loop();
				return weatherJSONObject;
			}

			// This gets executed on the UI thread
			protected void onPostExecute(JSONObject json) {
				// Your function that takes a json object and populates
				// views
				TextView t = (TextView) findViewById(R.id.main_textview);
				t.setBackgroundColor(0xFF0000);
				t.setTextColor(0xFFFFFF);
				t.setText(json.toString());

			}
		}

		FetchJSONDataTask task = new FetchJSONDataTask();
		task.execute(new String[] { "http://www.pixiewebdesign.net/apps/flight_info/results/view/departures/dublin" });

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_flight_info, menu);
		return true;
	}

	public static String readUrl(String urlString) throws Exception {
		BufferedReader reader = null;
		String str = "{}";
		try {
			URL url = new URL(urlString);
			reader = new BufferedReader(new InputStreamReader(url.openStream()));
			StringBuffer buffer = new StringBuffer();
			int read;
			char[] chars = new char[1024];
			while ((read = reader.read(chars)) != -1)
				buffer.append(chars, 0, read);

			str = buffer.toString();
		} catch (SocketException s) {
			str = "{ \"error\" : \"permission_denied\"}";
		} finally {
			if (reader != null)
				reader.close();
		}
		return str;

	}

}
